package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.event.model.OrderNewRushEvent;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.SmsTempletService;
import com.ybkj.daijia.server.service.ZhuancheService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class OrderNewRushListener implements ApplicationListener<OrderNewRushEvent> {

    private static final Logger logger = LoggerFactory.getLogger(OrderNewRushListener.class);

    @Autowired
    private SmsTempletService smsTempletService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private ErrandService errandService;

    @Autowired
    private ZhuancheService zhuanService;

    @Autowired
    private SettingUtils settingUtils;

    @Override
    @Async
    public void onApplicationEvent(OrderNewRushEvent event) {

        @SuppressWarnings("unchecked")
        List<Order> orders = (List<Order>) event.getSource();

        logger.debug("order newrush event:{}", orders.size());

        Order firstOrder = orders.get(0);

        Integer howLong = 0;
        if (firstOrder.getServerTime().getTime() - System.currentTimeMillis() > 1000 * 60 * 30) {
            howLong =
                (int) (firstOrder.getServerTime().getTime() - System.currentTimeMillis() - 1000 * 60 * 30)
                    / 1000;
        }

        final Timer timer = new Timer();
        final List<Order> newOrders = orders;
        timer.schedule(new TimerTask() {
            public void run() {

                Setting setting = settingUtils.get();
                //设备推送（新抢单）
                if (setting.isAllowRushOrder()) {

                    Double rushOrderKm1 = setting.getRushOrderKm1();
                    Double rushOrderKm2 = setting.getRushOrderKm2();
                    Double rushOrderKm3 = setting.getRushOrderKm3();
                    Integer rushOrderTime1 = setting.getRushOrderTime1();
                    Integer rushOrderTime2 = setting.getRushOrderTime2();
                    Integer rushOrderTime3 = setting.getRushOrderTime3();

                    try {
                        //第一阶段
                        Thread.sleep(rushOrderTime1 * 1000);
                        for (Order order : newOrders) {
                            Order newOrder = orderService.findOne(order.getId());
                            if (newOrder.getStatus().equals(Order.ORDER_STATUS_NEW)) {
                                List<Driver> drivers = driverService
                                    .queryNearly(newOrder.getClientLongitude(),
                                        newOrder.getClientLatitude(), rushOrderKm1,
                                        Driver.DriverJobType.daijia.toString());
                                if (!CollectionUtils.isEmpty(drivers)) {
                                    for (Driver rushDriver : drivers) {
                                        if (!rushDriver.getIsFreeze() && rushDriver.getStatus()
                                            .equals(Driver.DRIVER_ONLINE)) {
                                            if (rushDriver.getDriverJobType()
                                                .equals(Driver.DriverJobType.all) || rushDriver
                                                .getDriverJobType().toString()
                                                .contains(Driver.DriverJobType.daijia.toString())) {
                                                pushNewOrder(newOrder, rushDriver, setting);
                                            }
                                        }
                                    }
                                }
                            }
                            Thread.sleep(10000);
                        }
                        //第二阶段
                        Thread.sleep(rushOrderTime2 * 1000);
                        for (Order order : newOrders) {
                            Order newOrder = orderService.findOne(order.getId());
                            if (newOrder.getStatus().equals(Order.ORDER_STATUS_NEW)) {
                                List<Driver> drivers = driverService
                                    .queryNearly(newOrder.getClientLongitude(),
                                        newOrder.getClientLatitude(), rushOrderKm2,
                                        Driver.DriverJobType.daijia.toString());
                                if (!CollectionUtils.isEmpty(drivers)) {
                                    for (Driver rushDriver : drivers) {
                                        if (!rushDriver.getIsFreeze() && rushDriver.getStatus()
                                            .equals(Driver.DRIVER_ONLINE)) {
                                            if (rushDriver.getDriverJobType()
                                                .equals(Driver.DriverJobType.all) || rushDriver
                                                .getDriverJobType().toString()
                                                .contains(Driver.DriverJobType.daijia.toString())) {
                                                pushNewOrder(newOrder, rushDriver, setting);
                                            }
                                        }
                                    }
                                }
                            }
                            Thread.sleep(10000);
                        }
                        //第三阶段
                        Thread.sleep(rushOrderTime3 * 1000);
                        for (Order order : newOrders) {
                            Order newOrder = orderService.findOne(order.getId());
                            if (newOrder.getStatus().equals(Order.ORDER_STATUS_NEW)) {
                                List<Driver> drivers = driverService
                                    .queryNearly(newOrder.getClientLongitude(),
                                        newOrder.getClientLatitude(), rushOrderKm3,
                                        Driver.DriverJobType.daijia.toString());
                                if (!CollectionUtils.isEmpty(drivers)) {
                                    for (Driver rushDriver : drivers) {
                                        if (!rushDriver.getIsFreeze() && rushDriver.getStatus()
                                            .equals(Driver.DRIVER_ONLINE)) {
                                            if (rushDriver.getDriverJobType()
                                                .equals(Driver.DriverJobType.all) || rushDriver
                                                .getDriverJobType().toString()
                                                .contains(Driver.DriverJobType.daijia.toString())) {
                                                pushNewOrder(newOrder, rushDriver, setting);
                                            }
                                        }
                                    }
                                }
                            }
                            Thread.sleep(10000);
                        }

                    } catch (Exception e) {
                        logger.debug("push error : " + e.getMessage());
                    }

                }

                timer.cancel();
            }
        }, howLong * 1000);

    }

    private void pushNewOrder(Order newOrder, Driver rushDriver, Setting setting) {
        try {
            //发送设备推送
            PushDataV4 pushDataV4 = new PushDataV4();
            pushDataV4.setCode("0X02");
            pushDataV4.setData(newOrder.getId());
            pushDataV4.setType("0X00");
            pushDataV4.setSound("beep_2");
            Map<String, String> extra = new HashMap<String, String>();
            extra.put("content", "又有新工单可以抢啦");
            pushDataV4.setExtra(extra);

            boolean getuiOnline = false;
            if (StringUtils.isNotBlank(rushDriver.getUserID())) {
                getuiOnline = GeTuiEmployV4
                    .getClientOnline(rushDriver.getUserID(), settingUtils.get());
            }

            if (getuiOnline) {
                GeTuiEmployV4.push(rushDriver, pushDataV4, setting);
            } else {
                if (StringUtils.isNotBlank(rushDriver.getRegistrationId())) {
                    JiGuangEmployV4.push(rushDriver, pushDataV4, setting);
                }
            }

        } catch (Exception e) {
            logger.debug("push error : " + e.getMessage());
        }

    }

//	public Boolean getDriverBusy(Long employId){
//		if(employId!=null){
//			try {
//				ServiceSetting serviceSetting=ServiceUtil.checkOpen();
//				Long daijiaAmount=orderService.countActivedOrdersByDriver(employId);
//				if(daijiaAmount>0){
//					return true;
//				}
//				Long zhuancheAmount=zhuanService.countActivedOrdersByDriver(employId);
//				if(zhuancheAmount>0){
//					return true;
//				}
//				Long paotuiAmount=errandService.countBusyAmount(employId);
//				if(paotuiAmount>0){
//					return true;
//				}
//				return false;
//			}catch(Exception e){
//				e.printStackTrace();
//				return null;
//			}
//		}else{
//			return null;
//		}
//	}

}
